package timing.ukulele.project.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import timing.ukulele.project.mapper.DictionaryMapper;
import timing.ukulele.common.ResponseResult;
import timing.ukulele.common.ResultCode;
import timing.ukulele.common.portal.SystemData;
import timing.ukulele.persistent.service.BaseService;
import timing.ukulele.project.client.SystemClient;
import timing.ukulele.project.persistent.Dictionary;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DictionaryService extends BaseService<DictionaryMapper, Dictionary> {

    private final SystemClient systemService;

    public DictionaryService(SystemClient systemService) {
        this.systemService = systemService;
    }

    /**
     * 获取分页
     *
     * @param name    字典对象，可加查询条件
     * @param current 当前也页，从1开始
     * @param size    每页大小
     * @return 模板数据
     */
    public IPage<Dictionary> getPage(String name, String mySystem, int current, int size, HashMap<String, Object> map) {
        Page<Dictionary> page = new Page<>(current, size);
        LambdaQueryWrapper<Dictionary> query = new LambdaQueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            query.like(Dictionary::getName, name);
        }
        List<Long> systemIds = null;
        if (!"".equals(mySystem)) {
            String[] split = mySystem.split(",");
            if (!"0".equals(split[0])) {
                systemIds = Arrays.asList(split).stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
                query.in(Dictionary::getSystemId, systemIds);
            }
        }
        query.orderByDesc(Dictionary::getId);
        IPage<Dictionary> iPage = this.page(page, query);
        final ResponseResult<List<SystemData>> result = systemService.all();
        Map<Long, String> systemMap = null;
        if (result != null && result.getCode() == ResultCode.SUCCESS.getCode() && !CollectionUtils.isEmpty(result.getData())) {
            systemMap = result.getData().stream().collect(Collectors.toMap(SystemData::getId, SystemData::getName));
        }
        List<Dictionary> dictionaryList = iPage.getRecords();
        for (Dictionary dictionary : dictionaryList) {
            if (CollectionUtils.isEmpty(systemMap))
                dictionary.setSystemName("未知");
            else
                dictionary.setSystemName(systemMap.get(dictionary.getSystemId()));
        }
        return iPage;
    }

}
